import { useState, useRef } from "react";
import { View } from "@tarojs/components";
import Taro, { useLoad, navigateTo, useRouter, useDidShow } from "@tarojs/taro";
import { ItemView, SearchInput } from "../../components/index";
import { fetchList, fetchToCart } from "../../utils/api";
import "./index.scss";

const Index = () => {
  const [list, setList] = useState<any[]>([]);
  const router = useRouter();
  const routerPath = useRef("");
  const pageOpt = useRef({ page: 1, size: 5 });

  useDidShow(() => {
    console.log("index页面中", router.path);
    routerPath.current = router.path;
  });

  // 什么情况下可以让这个接口变成async接口
  // 答案：只要这个wx.request支持promise就可以变成async接口了

  // 处理数据初始化生命周期 类似于小程序中的生命周期onLoad
  useLoad(() => {
    fetchListData();
  });

  // 列表渲染接口
  const fetchListData = async () => {
    const response = await fetchList({ ...pageOpt.current });
    console.log("response:", response);
    setList(response);
  };

  // 详情
  const handleRouterDetail = (item) => {
    navigateTo({ url: `/pages/detail/detail?id=${item.id}` });
  };

  // search
  const handleRouterSearch = () => {
    console.log("search-------search");
    navigateTo({ url: `/pages/search/search` });
  };

  // 加入购物车
  const handleToCartClick = async (item) => {
    try {
      // 调用接口添加购物车
      const toCartRes = await fetchToCart({ item });
      console.log("ToCart", toCartRes);
      Taro.showToast({ title: "加入购物车", icon: "success" });
    } catch (error) {
      // reject => catch 一对 有reject 抛出，才能有catch接收
      // catch 如果想接受到内容？怎么做？答案：必须接收的reject出来的值
      console.log("error:", error);
      Taro.showToast({ title: "重复添加", icon: "error" });
    }
  };

  return (
    <View className="wrapper">
      {/* 首页  routerPath === ‘/pages/index/index*/}
      <SearchInput
        name="你好"
        disabled={true}
        onClick={handleRouterSearch}
        onChange={() => {}}
      ></SearchInput>

      {list.map((item) => {
        return (
          <ItemView
            // useRef 是通过current传递值的
            routerPath={routerPath.current}
            key={item.id}
            item={item}
            detailClick={() => handleRouterDetail(item)}
            toCartClick={() => handleToCartClick(item)}
            src={item.productPic}
            text={item.productName}
          ></ItemView>
        );
      })}
    </View>
  );
};

export default Index;
/**id: "610000201807261282"
isSelected: false
number: 1
price: 84.695806
productInfo: "温求八电级拉门统生备对最没。"
productName: "选水部品度身该后存品米示又治成者。"
productPic: "http://dummyimage.com/100×100/fb0a2a"
userId: 1 */
